<!DOCTYPE html>
<html lang="ch">
<head>
    <meta charset="UTF-8">
    <title>BBChat</title>

    <link rel="stylesheet" href="layui/css/layui.css" />
    <link rel="stylesheet" href="css/index.css"/>

</head>
<body class="layui-layout-body" style="border:1px solid #f0f0f0;margin-left: 10%;margin-right: 10%;margin-top:50px;border-radius: 3px">
    <div class = "layui-row" style="background-color: #f0f0f0;">
        <div class="layui-col-md8" style="padding: 5px;height: 500px">
            <div class="layui-card" style="height: 100%">
                <div id="chatUser" class="layui-card-header" style="text-align: center">
                    BBChat
                </div>
                <div class="layui-card-body" style="height: 100%">
                    <div id="div_content" style="height: 55%;overflow: auto">
                        <!--消息体-->
                        <ul id="message">

                        </ul>
                        <div><a href="#1" name="1" id="msg_end">&nbsp;</a></div>
                    </div>

                    <!--工具栏-->
                    <div style="padding-left: 20px;">
                        <button id="expression" class="toolBtn" onclick="alterExpression()"><i class="layui-icon layui-icon-face-smile-b"></i></button>
                        <button class="toolBtn"><i class="layui-icon layui-icon-picture"></i></button>
                        <button class="toolBtn" style="float:right;"><i class="layui-icon layui-icon-log"></i></button>
                    </div>

                    <!--分割线-->
                    <hr>

                    <!--输入框-->
                    <div>
                        <form action="" class="layui-form">
                            <div class="layui-form-item layui-form-text">
                                <div class="layui-input-inline" style="width: 80%">
                                    <input type="hidden" name="fromUser" id="username">
                                    <input type="hidden" name="toUser" id="to">
                                    <textarea id="content" name="msg" placeholder="请输入内容" class="layui-textarea" style="border:0px;resize:none"></textarea>
                                </div>
                                <div class="layui-input-inline" style="padding-top: 40px;padding-left: 20px;">
                                    <button id="subBtn" class="layui-btn layui-btn-sm" lay-submit lay-filter="chatForm">发送</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-md4" style="padding: 5px;height: 500px">
            <div class="layui-card" style="height: 100%">
                <div class="layui-card-header">
                    <h3>在线列表</h3>
                </div>
                <div class="layui-card-body">
                    <ul class="onLineUser" id="onLineUser">
                    </ul>
                </div>
            </div>
        </div>
    </div>
</body>

<!--表情框弹出层-->
<div style="display: none;" id="expressionAlter"></div>

<script src="layui/layui.js"></script>

<script>
    var isInThisPage = true;
    var isNewMessage = false;
    var layer = null;
    var $ = null;
    var lastUpdateTime = 0;

    layui.use(['element','form'],function(){
        var element = layui.element;
        var form = layui.form;
        layer = layui.layer;
        $ = layui.$;

        //加载表情
        loadExpressions();

        var username = prompt("请输入您的用户名");
        $('#username').val(username);

        form.on('submit(chatForm)',function (data) {
            console.log(data.field);

            if(data.field.msg.trim() != '')
                sendMessage(data.field);
            //清空消息
            $('#content').val('');

            return false;
        })

        function getWebSocket() {
            var host = window.location.host;
            var url = 'ws:/'+host+'/chat/'+username;
            var webSocket = new WebSocket(url);

            webSocket.onopen = function (ev) {
                console.log("webSocket打开连接");
            }

            webSocket.onmessage = function (ev) {
                console.log('WebSocket收到消息：%c' + ev.data, 'color:green');
                var data = JSON.parse(ev.data);
                console.log(data);
                if(data.type == 'ENTER'){
                    layer.msg(data.fromUser+'进入聊天室');
                    getOnLineUser();
                }else if(data.type == 'SPEAK'){
                    if(username == data.fromUser){
                        //是自己发送的消息
                        addMessageItem(data.msg,data.fromUser,true);
                    }else{
                        //不是自己发的
                        addMessageItem(data.msg,data.fromUser,false);
                    }

                    $('#div_content').scrollTop($('#div_content')[0].scrollHeight);


                    if(!isInThisPage || document.visibilityState == 'hidden'){
                        isNewMessage = true;
                        document.title = "[新消息]";
                    }

                }else if(data.type == 'QUIT'){
                    layer.msg(data.fromUser+'退出聊天室');
                    getOnLineUser();
                }
            }

            webSocket.onclose = function (ev) {
                console.log("webSocket连接关闭");
            }

            webSocket.onerror = function (ev) {
                console.log("webSocket发生异常");
            }

            return webSocket;
        }

        var webSocket = getWebSocket();

        function sendMessage(message) {
            webSocket.send(JSON.stringify(message));
        }

        function getOnLineUser() {
            $.ajax({
                url:window.location.protocol+'//'+window.location.host+'/getOnlineUser',
                method:'POST',
                async:false,
                success:function (data) {
                    console.log(data);
                    $('#onLineUser').empty();
                    for (var i = 0; i < data.length; i++) {
                        $('#onLineUser').append($('<li class="userList">'+data[i]+'</li>'));
                    }
                    /*$('.userList').click(function () {
                        var user = $(this).text();
                        //设置聊天对象
                        $('#chatUser').text(user);
                        $('#to').val(user);
                        flag = true;
                    })*/
                },
                error:function (data) {
                    alert('error');
                },
                type:'json'
            });
        }

        //回车键发送消息
        $(document).keyup(function(event){
            if(event.keyCode==13){
                $('#subBtn').click();
            }
        })

        window.onfocus = function(){
            isInThisPage = true;
            isNewMessage = false;
            document.title = "BBChat";
        }

        window.onblur = function(){
            isInThisPage = false;
        }

        //设置定时，如果有新消息闪烁标题
        setInterval(function flashTitle(){
            if(!isInThisPage && isNewMessage){
                if(document.title == 'BBChat'){
                    document.title = '[新消息]';
                }else{
                    document.title = 'BBChat';
                }
            }
        },1000);

        /**
         * 增加消息
         */
        function addMessageItem(msg,fromUser,isSendMessage){
            //计算是否显示时间
            // debugger;
            var date = new Date();
            var t = date-lastUpdateTime;
            var timeHtml = '';
            if(t/1000/60 > 2){
                timeHtml = '<div style="color:silver;text-align: center">'+ dateFormat("YYYY年mm月dd HH:MM:SS",date) + '</div>';
            }
            lastUpdateTime = date;

            var headPhotoStyle = '';
            var messageStyle = '';
            if(isSendMessage){
                headPhotoStyle = 'float:right;background-color:#5FB878';
                messageStyle = 'float:right;background-color:#009688;color:white;';
            }else{
                headPhotoStyle = 'float:left;background-color:#2F4056;';
                messageStyle = 'float:left;background-color:#f0f0f0;color:black;';
            }

            var msgHtml = '<li style="margin-top:5px;">' +
                '<div>' +
                 timeHtml +
                '<div class="headPhoto" style="'+headPhotoStyle+'">'+ fromUser[0].toUpperCase() + '</div>' +
                '<div class="message" style="'+messageStyle+'">'+ msg +'</div>' +
                '</div>' +
                '</li><div style="clear: both"></div>';
            // console.log(msgHtml);
            $('#message').append(msgHtml);
        }

        /**
         * 格式化日期
         */
        function dateFormat(fmt, date) {
            let ret;
            let opt = {
                "Y+": date.getFullYear().toString(),        // 年
                "m+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "M+": date.getMinutes().toString(),         // 分
                "S+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
            };
            return fmt;
        }
    })

    /**
     * 表情框弹窗
     */
    function alterExpression(){
        layer.open({
            type:1,
            content:$('#expressionAlter'),
            title:'颜文字',
            shade:0.1,
            shadeClose:true,
            area:['500px','300px']
        })
    }

    /**
     * 点击表情，并将表情界面关闭
     */
    function useExpression(obj){
        $('#content').val($('#content').val()+obj.innerText);
        layer.closeAll();
    }

    /**
     * 读取本地文件
     * @param name
     * @returns {any}
     */
    function loadFile(name) {
        let xhr = new XMLHttpRequest(),
            okStatus = document.location.protocol === "file:" ? 0 : 200;
        xhr.open('GET', name, false);
        xhr.overrideMimeType("text/html;charset=utf-8");//默认为utf-8
        xhr.send(null);
        return xhr.status === okStatus ? xhr.responseText : null;
    }

    /**
     * 加载颜文字
     */
    function loadExpressions(){
        var text = loadFile("expression.config");
        var expressions = text.split('\n');

        for (var i = 0; i < expressions.length; i++) {
            var expression = expressions[i];
            var htmlStr = "<div class=\"expressionBtn\" onclick=\"useExpression(this)\">"+expression+"</div>";
            $('#expressionAlter').append(htmlStr);
        }
    }
</script>



</html>